package com.duan.laugh.sms.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.util.List;

/**
 * reids中的短信账户
 *
 * @author duanjw
 */
public class RedisSmsAccountRepository implements SmsAccountRepository {
    /**
     * 短信账户redis中的key
     */
    private final String smsAccountKey = "sms::accounts::key";
    private RedisTemplate redisTemplate;

    public RedisSmsAccountRepository(RedisConnectionFactory redisConnectionFactory) {
        redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        final Jackson2JsonRedisSerializer<SmsAccount> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(SmsAccount.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 支持JAVA8时间格式
        objectMapper.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        redisTemplate.setKeySerializer(redisTemplate.getStringSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(redisTemplate.getStringSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
    }

    /**
     * 所有短信账户
     * @return
     */
    @Override
    public List<SmsAccount> getSmsAccounts() {
        return redisTemplate.opsForHash().values(smsAccountKey);
    }

    /**
     * 根据短信账户id获取短信账户
     * @param id
     * @return
     */
    @Override
    public SmsAccount getSmsAccount(String id) {
        return (SmsAccount) redisTemplate.opsForHash().get(smsAccountKey, id);
    }

    /**
     * 新增短信账户
     * @param smsAccount
     */
    @Override
    public void add(SmsAccount smsAccount) {
        redisTemplate.opsForHash().put(smsAccountKey, smsAccount.getId(), smsAccount);
    }

    /**
     * 根据id删除短信账户
     * @param id
     */
    @Override
    public void delete(String id) {
        redisTemplate.opsForHash().delete(smsAccountKey, id);
    }
}
